package com.ylt.graduation;

import java.io.File;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;

public class MainActivity extends MapActivity {

	BMapManager mBMapMan = null;
	MKLocationManager mLocationManager = null;
	LocationListener mLocationListener = null; // onResume时注册此listener，onPause时需要Remove
	MyLocationOverlay mLocationOverlay = null; // 定位图层
	MapView mMapView = null;
	RunLineOverlay mRunLine = null;
	final int TAKE_PICTURE = 23023;// 为了表示返回方法中辨识你的程序打开的相机

	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/ylt/Photos");
	private File mCurrentPhotoFile;// 照相机拍照得到的图片
	String FileName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		GraduApp app = (GraduApp) this.getApplication();
		if (app.mBMapMan != null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new GraduApp.MyGeneralListener());
		}
		app.mBMapMan.start();
		super.initMapActivity(app.mBMapMan);

		mMapView = (MapView) findViewById(R.id.bmapsView);
		mMapView.setBuiltInZoomControls(true); // 设置启用内置的缩放控件
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);

		MapController mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
		// GeoPoint point = new GeoPoint((int) (39.915 * 1E6),
		// (int) (116.404 * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
		// mMapController.setCenter(point); // 设置地图中心点
		mMapController.setZoom(18); // 设置地图zoom级别

		// 初始化Location模块
		// mLocationManager = mBMapMan.getLocationManager();
		// 通过enableProvider和disableProvider方法，选择定位的Provider
		// mLocationManager.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		// mLocationManager.disableProvider(MKLocationManager.MK_GPS_PROVIDER);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mMapView);
		mMapView.getOverlays().add(mLocationOverlay);
		mLocationOverlay.enableCompass();// 启用指南针
		mLocationOverlay.enableMyLocation();// 启用定位

		// 注册定位事件
		mLocationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				if (location != null) {
					GeoPoint pt = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
					if (mRunLine == null) {
						mRunLine = new RunLineOverlay();
						mRunLine.addGeoPoint(pt);
						mMapView.getOverlays().add(mRunLine);
					} else
						mRunLine.addGeoPoint(pt);
					mMapView.getController().animateTo(pt);
				}
			}
		};
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		GraduApp app = (GraduApp) this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mLocationOverlay.disableMyLocation();
		mLocationOverlay.disableCompass(); // 关闭指南针
		app.mBMapMan.stop();
		super.onPause();
	}

	@Override
	protected void onResume() {
		GraduApp app = (GraduApp) this.getApplication();
		// 注册定位事件，定位后将地图移动到定位点
		app.mBMapMan.getLocationManager().requestLocationUpdates(
				mLocationListener);
		mLocationOverlay.enableMyLocation();
		mLocationOverlay.enableCompass(); // 打开指南针
		app.mBMapMan.start();
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.main, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {
		case R.id.take_pic:
			String status = Environment.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
				doTakePhoto();// 用户点击了从照相机获取
			} else {
				Toast.makeText(MainActivity.this, "没有SD卡", Toast.LENGTH_LONG)
						.show();
			}
			break;
		case R.id.suggestion:

			break;
		case R.id.map_guide:

			break;
		case R.id.voice_sugg:

			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == TAKE_PICTURE) {
			if (resultCode == RESULT_OK) {
				File f = new File(PHOTO_DIR, FileName);
				if (f.exists()) {
					// 此外，你还可以使用BitmapFactory的decodeResource方法获得一个Bitmap对象
					// 使用decodeResource方法时传入的是一个drawable的资源id
					// 还有一个decodeStream方法，这个方法传入一个图片文件的输入流即可！
					// bm = BitmapFactory.decodeFile(f.getAbsolutePath());
					// 设置ImageView的显示图片
					// imageViewPhoto.setImageBitmap(bm);
					Toast.makeText(getApplicationContext(), FileName,
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, "文件不存在！", Toast.LENGTH_SHORT).show();
					return;
				}
			}
		}
	}

	/**
	 * 获取访问SD卡中图片路径
	 * 
	 * @return
	 */
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			if (!PHOTO_DIR.exists()) {
				boolean iscreat = PHOTO_DIR.mkdirs();// 创建照片的存储目录
				Log.e("YAO", "" + iscreat);
			}
			FileName = System.currentTimeMillis() + ".jpg";
			mCurrentPhotoFile = new File(PHOTO_DIR, FileName);
			Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, TAKE_PICTURE);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "photoPickerNotFoundText", Toast.LENGTH_LONG)
					.show();
		}
	}

}
